<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>个性化旅游系统</title>
    <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/5.15.4/css/all.min.css">
    <script type="text/javascript" src="https://api.map.baidu.com/api?v=3.0&ak=gfXEYso6gF84SwIw29zwwFDyxWOrWMzy"></script>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }
        body {
            font-family: 'Microsoft YaHei', sans-serif;
            height: 100vh;
            overflow: hidden;
            background-color: #f5f5f5;
        }
        .container {
            display: flex;
            height: 100vh;
        }
        .side-menu {
            width: 25%;
            height: 100vh;
            position: fixed;
            right: 0;
            display: flex;
            flex-direction: column;
            align-items: center;
            padding-top: 50px;
            gap: 30px;
            background-color: #f5f5f5;
        }
        .module-box {
            width: 80%;
            height: 120px;
            background-color: #fff;
            border-radius: 10px;
            box-shadow: 0 4px 10px rgba(0, 0, 0, 0.1);
            display: flex;
            flex-direction: column;
            justify-content: center;
            align-items: center;
            cursor: pointer;
            transition: transform 0.3s, box-shadow 0.3s;
        }
        .module-box:hover {
            transform: translateY(-5px);
            box-shadow: 0 6px 15px rgba(0, 0, 0, 0.15);
        }
        .module-icon {
            font-size: 32px;
            margin-bottom: 10px;
        }
        .module-title {
            font-size: 18px;
            font-weight: bold;
            color: #333;
        }
        .content-area {
            width: 75%;
            height: 100vh;
            display: flex;
            justify-content: center;
            align-items: center;
            background-color: #f9f9f9;
        }
        .search-container {
            width: 100%;
            max-width: 100%;
            display: flex;
            margin-top: 0;
            padding-top: 20px;
            flex-direction: column;
            align-items: center;
        }
        .search-title {
            color: #333;
            font-size: 24px;
            margin-bottom: 20px;
        }
        .search-input-group {
            display: flex;
            width: 100%;
        }
        .search-input {
            flex: 1;
            padding: 15px;
            font-size: 18px;
            border: none;
            border-radius: 5px 0 0 5px;
            outline: none;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }
        .search-button {
            padding: 15px 20px;
            background-color: #4CAF50;
            color: white;
            border: none;
            border-radius: 0 5px 5px 0;
            cursor: pointer;
            font-size: 18px;
        }
        .search-button:hover {
            background-color: #45a049;
        }
        .welcome-message {
            font-size: 32px;
            color: #666;
            text-align: center;
        }
        .icon-locations {
            color: #3498db;
        }
        .icon-food {
            color: #e74c3c;
        }
        .icon-travel-log {
            color: #2ecc71;
        }
        .icon-post {
            color: #9b59b6;
        }
        .search-results-area {
            width: 100%;
            margin-top: 20px;
            display: flex;
            flex-direction: column;
            align-items: center;
            overflow-y: auto;
            max-height: calc(100vh - 150px);
        }
        #map {
            width: 100%;
            height: 100%;
        }
    </style>
</head>
<body>
    <div class="container">
        <div class="content-area" id="content-area">
            <!-- 左侧显示地图 -->
            <div id="map"></div>
        </div>
        
        <div class="side-menu" id="side-menu">
            <!-- 地点模块 -->
            <div class="module-box" onclick="showPlacesModule()">
                <i class="fas fa-landmark module-icon icon-locations"></i>
                <div class="module-title">地点</div>
            </div>
            <!-- 美食模块 -->
            <div class="module-box" onclick="showModuleContent('food')">
                <i class="fas fa-utensils module-icon icon-food"></i>
                <div class="module-title">美食</div>
            </div>
            <!-- 路线规划模块 -->
            <div class="module-box" onclick="showRoutePanel()">
                <i class="fas fa-route module-icon" style="color: #f39c12;"></i>
                <div class="module-title">路线规划</div>
            </div>
            <!-- 旅游日志模块 -->
            <div class="module-box" onclick="window.location.href='travel_logs.html'">
                <i class="fas fa-book module-icon icon-travel-log"></i>
                <div class="module-title">旅游日志</div>
            </div>
            <!-- 发布动态模块 -->
            <div class="module-box" onclick="window.location.href='post.html'">
                <i class="fas fa-edit module-icon icon-post"></i>
                <div class="module-title">发布动态</div>
            </div>
        </div>
    </div>

    <script>
        // 全局变量
        var map;
        var markers = [];
        var routePlanningMarkers = [];
        var routeLines = [];
        var startMarker, endMarker;
        var currentSortMethod = "popularity"; // 默认按热度排序
        var placesData = []; // 存储所有地点数据的全局变量
        
        // 初始化地图
        window.onload = function() {
            console.log("页面初始化...");
            
            // 先获取全局地点数据
            refreshPlacesData()
                .then(() => {
                    console.log("全局数据加载完成，初始化地图...");
                    
                    // 初始化百度地图
                    map = new BMap.Map("map");
                    
                    // 设置地图中心点为北京市中心，缩放级别为12
                    var beijingCenter = new BMap.Point(116.404, 39.915);
                    map.centerAndZoom(beijingCenter, 12);
                    
                    // 启用鼠标滚轮缩放
                    map.enableScrollWheelZoom(true);
                    
                    // 添加地图控件
                    map.addControl(new BMap.NavigationControl());     // 导航控件
                    map.addControl(new BMap.ScaleControl());          // 比例尺控件
                    map.addControl(new BMap.OverviewMapControl());    // 缩略图控件
                    map.addControl(new BMap.MapTypeControl());        // 地图类型控件
                    
                    // 显示北京市边界
                    showBeijingBoundary(map);
                    
                    // 加载地点数据到地图
                    loadPlaces(map);
                })
                .catch(error => {
                    console.error("初始化失败:", error);
                    alert("加载数据失败，请刷新页面重试");
                });
        };
        
        // 显示北京市边界
        function showBeijingBoundary(map) {
            var bdary = new BMap.Boundary();
            bdary.get("北京市", function(rs) {
                var count = rs.boundaries.length;
                if (count === 0) {
                    console.error('未能获取北京市边界');
                    return;
                }
                
                for (var i = 0; i < count; i++) {
                    var ply = new BMap.Polygon(rs.boundaries[i], {
                        strokeWeight: 2,
                        strokeColor: "#ff6600",
                        fillColor: "",
                        fillOpacity: 0.2
                    });
                    map.addOverlay(ply);
                }
            });
        }
        
        // 加载地点数据
        function loadPlaces(map) {
            console.log("正在加载地点数据...");
            // 清空现有标记
            for (var i = 0; i < markers.length; i++) {
                map.removeOverlay(markers[i]);
            }
            markers = [];
            
            // 更新全局地点数据
            refreshPlacesData()
                .then(() => {
                    // 使用全局数据创建地图标记
                    console.log(`成功加载 ${placesData.length} 个地点`);
                    
                    placesData.forEach(place => {
                        var point = new BMap.Point(place.longitude, place.latitude);
                        var marker = new BMap.Marker(point);
                        
                        // 设置标记的自定义属性
                        marker.placeId = place.id;
                        marker.placeName = place.name;
                        marker.placeType = place.type;
                        
                        // 添加标记点击事件
                        marker.addEventListener("click", function() {
                            // 调用地点详情API增加热度
                            fetch(`/api/places/${place.id}`)
                                .then(response => {
                                    if (!response.ok) {
                                        throw new Error('获取地点详情失败');
                                    }
                                    return response.json();
                                })
                                .then(updatedPlace => {
                                    console.log(`地点 ${updatedPlace.name} 热度增加到 ${updatedPlace.popularity}`);
                                    
                                    // 更新全局数据中的地点信息
                                    updatePlaceInGlobalData(updatedPlace);
                                    
                                    // 更新content中的热度和评价
                                    var content = `
                                        <div style="max-width: 300px;">
                                            <h3 style="margin: 5px 0; color: #d00;">${updatedPlace.name}</h3>
                                            <p><strong>类型:</strong> ${updatedPlace.type}</p>
                                            <p><strong>地址:</strong> ${updatedPlace.address || '未知'}</p>
                                            <p>${updatedPlace.description || ''}</p>
                                            <div style="display: flex; margin-top: 10px; font-size: 13px;">
                                                <div style="display: flex; align-items: center; margin-right: 15px;">
                                                    <i class="fas fa-fire" style="color: #f39c12; margin-right: 5px;"></i>
                                                    <span>热度: ${parseFloat(updatedPlace.popularity).toFixed(1)}</span>
                                                </div>
                                                <div style="display: flex; align-items: center;">
                                                    <i class="fas fa-star" style="color: #f1c40f; margin-right: 5px;"></i>
                                                    <span>评价: ${updatedPlace.rating ? parseFloat(updatedPlace.rating).toFixed(1) : '暂无'}</span>
                                                </div>
                                            </div>
                                            <div style="margin-top: 10px;">
                                                <button onclick="ratePlace(${updatedPlace.id})" style="padding: 5px 10px; background-color: #2ecc71; color: white; border: none; border-radius: 3px; cursor: pointer;">
                                                    <i class="fas fa-star"></i> 评价此地点
                                                </button>
                                                <button onclick="window.location.href='/place/${updatedPlace.id}'" style="padding: 5px 10px; background-color: #3498db; color: white; border: none; border-radius: 3px; cursor: pointer; margin-left: 5px;">
                                                    <i class="fas fa-map-marked-alt"></i> 查看详细地图
                                                </button>
                                            </div>
                                            <div style="margin-top: 5px; font-size: 12px; color: #777; text-align: center;">
                                                页面将在3秒后自动跳转到详细地图...
                                            </div>
                                        </div>
                                    `;
                                    
                                    var infoWindow = new BMap.InfoWindow(content);
                                    marker.openInfoWindow(infoWindow);
                                    
                                    // 添加3秒后自动跳转到单点地图页面
                                    setTimeout(function() {
                                        window.location.href = `/place/${updatedPlace.id}`;
                                    }, 3000);
                                    
                                    // 如果推荐列表正在显示，则刷新
                                    if (document.getElementById('places-results')) {
                                        displayPlacesFromGlobalData();
                                    }
                                })
                                .catch(error => {
                                    console.error('获取地点详情失败:', error);
                                    // 如果API调用失败，显示原始信息窗口
                                    var content = `
                                        <div style="max-width: 300px;">
                                            <h3 style="margin: 5px 0; color: #d00;">${place.name}</h3>
                                            <p><strong>类型:</strong> ${place.type}</p>
                                            <p><strong>地址:</strong> ${place.address || '未知'}</p>
                                            <p>${place.description || ''}</p>
                                            <div style="margin-top: 10px;">
                                                <button onclick="window.location.href='/place/${place.id}'" style="padding: 5px 10px; background-color: #3498db; color: white; border: none; border-radius: 3px; cursor: pointer;">
                                                    <i class="fas fa-map-marked-alt"></i> 查看详细地图
                                                </button>
                                            </div>
                                        </div>
                                    `;
                                    var infoWindow = new BMap.InfoWindow(content);
                                    marker.openInfoWindow(infoWindow);
                                    
                                    // 即使获取详情失败，也在3秒后跳转
                                    setTimeout(function() {
                                        window.location.href = `/place/${place.id}`;
                                    }, 3000);
                                });
                        });
                        
                        // 添加到地图
                        map.addOverlay(marker);
                        markers.push(marker);
                    });
                    
                    // 调整地图视图以包含所有标记
                    if (markers.length > 0) {
                        var points = markers.map(marker => marker.getPosition());
                        map.setViewport(points);
                    }
                })
                .catch(error => {
                    console.error('加载地点数据失败:', error);
                    alert('加载地点数据失败，请检查服务器连接');
                });
        }
        
        // 刷新全局地点数据
        function refreshPlacesData() {
            return fetch('/api/places')
                .then(response => {
                    if (!response.ok) {
                        throw new Error('网络请求失败: ' + response.status);
                    }
                    return response.json();
                })
                .then(places => {
                    placesData = places; // 更新全局数据
                    console.log(`全局数据更新：${placesData.length} 个地点`);
                    return places;
                });
        }
        
        // 在全局数据中更新单个地点信息
        function updatePlaceInGlobalData(updatedPlace) {
            for (var i = 0; i < placesData.length; i++) {
                if (placesData[i].id === updatedPlace.id) {
                    placesData[i] = updatedPlace;
                    console.log(`全局数据更新：地点 ${updatedPlace.name} 的信息已更新`);
                    break;
                }
            }
        }

        function showModuleContent(moduleType) {
            const contentArea = document.getElementById('content-area');
            const sideMenu = document.getElementById('side-menu');
            let title, iconClass, color;
            
            switch(moduleType) {
                case 'locations':
                    title = '搜索旅游地点';
                    iconClass = 'fa-landmark';
                    color = '#3498db';
                    break;
                case 'food':
                    title = '搜索美食';
                    iconClass = 'fa-utensils';
                    color = '#e74c3c';
                    break;
            }
            
            // 保存地图内容，稍后恢复
            const mapContent = contentArea.innerHTML;
            
            // 替换右侧菜单为搜索框，放置在右侧1/4顶部
            var menuHtml = "<div class=\"search-container\">";
            menuHtml += "    <div class=\"search-title\">";
            menuHtml += "        <i class=\"fas " + iconClass + "\" style=\"margin-right: 10px; color: " + color + ";\"></i>";
            menuHtml += "        " + title;
            menuHtml += "    </div>";
            menuHtml += "    <div class=\"search-input-group\">";
            menuHtml += "        <input type=\"text\" class=\"search-input\" placeholder=\"请输入关键词搜索...\">";
            menuHtml += "        <button class=\"search-button\">";
            menuHtml += "            <i class=\"fas fa-search\"></i> 搜索";
            menuHtml += "        </button>";
            menuHtml += "    </div>";
            menuHtml += "</div>";
            menuHtml += "<div style=\"margin-top: 20px;\">";
            menuHtml += "    <button onclick=\"resetInterface()\" style=\"padding: 10px 15px; background-color: #f1f1f1; border: 1px solid #ddd; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "        <i class=\"fas fa-arrow-left\"></i> 返回";
            menuHtml += "    </button>";
            menuHtml += "</div>";
            sideMenu.innerHTML = menuHtml;
        }
        
        function resetInterface() {
            // 重置为初始状态
            const contentArea = document.getElementById('content-area');
            const sideMenu = document.getElementById('side-menu');
            
            var menuHtml = "<!-- 地点模块 -->";
            menuHtml += "<div class=\"module-box\" onclick=\"showPlacesModule()\">";
            menuHtml += "    <i class=\"fas fa-landmark module-icon icon-locations\"></i>";
            menuHtml += "    <div class=\"module-title\">地点</div>";
            menuHtml += "</div>";
            menuHtml += "<!-- 美食模块 -->";
            menuHtml += "<div class=\"module-box\" onclick=\"showModuleContent('food')\">";
            menuHtml += "    <i class=\"fas fa-utensils module-icon icon-food\"></i>";
            menuHtml += "    <div class=\"module-title\">美食</div>";
            menuHtml += "</div>";
            menuHtml += "<!-- 路线规划模块 -->";
            menuHtml += "<div class=\"module-box\" onclick=\"showRoutePanel()\">";
            menuHtml += "    <i class=\"fas fa-route module-icon\" style=\"color: #f39c12;\"></i>";
            menuHtml += "    <div class=\"module-title\">路线规划</div>";
            menuHtml += "</div>";
            menuHtml += "<!-- 旅游日志模块 -->";
            menuHtml += "<div class=\"module-box\" onclick=\"window.location.href='travel_logs.html'\">";
            menuHtml += "    <i class=\"fas fa-book module-icon icon-travel-log\"></i>";
            menuHtml += "    <div class=\"module-title\">旅游日志</div>";
            menuHtml += "</div>";
            menuHtml += "<!-- 发布动态模块 -->";
            menuHtml += "<div class=\"module-box\" onclick=\"window.location.href='post.html'\">";
            menuHtml += "    <i class=\"fas fa-edit module-icon icon-post\"></i>";
            menuHtml += "    <div class=\"module-title\">发布动态</div>";
            menuHtml += "</div>";
            sideMenu.innerHTML = menuHtml;
            
            // 清除路线规划相关覆盖物
            clearRoutePlanningOverlays();
        }
        
        // 显示路线规划面板
        function showRoutePanel() {
            const sideMenu = document.getElementById('side-menu');
            
            var menuHtml = "<div class=\"search-container\">";
            menuHtml += "    <div class=\"search-title\">";
            menuHtml += "        <i class=\"fas fa-route\" style=\"margin-right: 10px; color: #f39c12;\"></i>";
            menuHtml += "        路线规划";
            menuHtml += "    </div>";
            
            menuHtml += "    <div style=\"margin: 15px 0;\">";
            menuHtml += "        <p style=\"margin-bottom: 5px; font-weight: bold;\">起点</p>";
            menuHtml += "        <div style=\"display: flex; gap: 5px;\">";
            menuHtml += "            <input type=\"text\" id=\"start-input\" class=\"search-input\" placeholder=\"输入起点或点击地图选择\" style=\"border-radius: 5px;\">";
            menuHtml += "            <button onclick=\"searchLocation('start')\" style=\"padding: 0 10px; background-color: #3498db; color: white; border: none; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "                <i class=\"fas fa-search\"></i>";
            menuHtml += "            </button>";
            menuHtml += "        </div>";
            menuHtml += "    </div>";
            
            menuHtml += "    <div style=\"margin: 15px 0;\">";
            menuHtml += "        <p style=\"margin-bottom: 5px; font-weight: bold;\">终点</p>";
            menuHtml += "        <div style=\"display: flex; gap: 5px;\">";
            menuHtml += "            <input type=\"text\" id=\"end-input\" class=\"search-input\" placeholder=\"输入终点或点击地图选择\" style=\"border-radius: 5px;\">";
            menuHtml += "            <button onclick=\"searchLocation('end')\" style=\"padding: 0 10px; background-color: #3498db; color: white; border: none; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "                <i class=\"fas fa-search\"></i>";
            menuHtml += "            </button>";
            menuHtml += "        </div>";
            menuHtml += "    </div>";
            
            menuHtml += "    <div style=\"margin: 15px 0;\">";
            menuHtml += "        <p style=\"margin-bottom: 5px; font-weight: bold;\">出行方式</p>";
            menuHtml += "        <div style=\"display: flex; gap: 10px;\">";
            menuHtml += "            <label style=\"display: flex; align-items: center;\">";
            menuHtml += "                <input type=\"radio\" name=\"route-type\" value=\"driving\" checked style=\"margin-right: 5px;\"> 驾车";
            menuHtml += "            </label>";
            menuHtml += "            <label style=\"display: flex; align-items: center;\">";
            menuHtml += "                <input type=\"radio\" name=\"route-type\" value=\"walking\" style=\"margin-right: 5px;\"> 步行";
            menuHtml += "            </label>";
            menuHtml += "            <label style=\"display: flex; align-items: center;\">";
            menuHtml += "                <input type=\"radio\" name=\"route-type\" value=\"transit\" style=\"margin-right: 5px;\"> 公交";
            menuHtml += "            </label>";
            menuHtml += "        </div>";
            menuHtml += "    </div>";
            
            menuHtml += "    <button onclick=\"planRoute()\" style=\"width: 100%; padding: 10px 0; background-color: #f39c12; color: white; border: none; border-radius: 5px; cursor: pointer; font-size: 16px; margin-top: 15px;\">";
            menuHtml += "        <i class=\"fas fa-route\"></i> 开始规划";
            menuHtml += "    </button>";
            
            menuHtml += "    <div id=\"route-result\" style=\"margin-top: 15px; max-height: 300px; overflow-y: auto;\"></div>";
            
            menuHtml += "</div>";
            menuHtml += "<div style=\"margin-top: 20px;\">";
            menuHtml += "    <button onclick=\"resetInterface()\" style=\"padding: 10px 15px; background-color: #f1f1f1; border: 1px solid #ddd; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "        <i class=\"fas fa-arrow-left\"></i> 返回";
            menuHtml += "    </button>";
            menuHtml += "</div>";
            
            sideMenu.innerHTML = menuHtml;
            
            // 启用基本的地图点击事件，用于选择起点和终点
            enableMapClickForRoutePlanning();
        }
        
        // 清除路线规划相关覆盖物
        function clearRoutePlanningOverlays() {
            // 清除起终点标记
            if (startMarker) {
                map.removeOverlay(startMarker);
                startMarker = null;
            }
            if (endMarker) {
                map.removeOverlay(endMarker);
                endMarker = null;
            }
            
            // 清除路线
            for (var i = 0; i < routeLines.length; i++) {
                map.removeOverlay(routeLines[i]);
            }
            routeLines = [];
        }
        
        // 启用地图点击事件，用于选择起点和终点
        function enableMapClickForRoutePlanning() {
            // 清除已有的路线规划相关覆盖物
            clearRoutePlanningOverlays();
            
            // 监听地图点击事件
            map.addEventListener("click", function(e) {
                var point = e.point;
                
                // 判断是设置起点还是终点
                if (!startMarker) {
                    // 设置起点
                    startMarker = new BMap.Marker(point);
                    startMarker.setIcon(new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(23, 25)));
                    startMarker.setLabel(new BMap.Label("起点", {offset: new BMap.Size(20, 0)}));
                    map.addOverlay(startMarker);
                    
                    // 更新起点输入框
                    var gc = new BMap.Geocoder();
                    gc.getLocation(point, function(rs) {
                        var address = rs.address;
                        document.getElementById("start-input").value = address;
                    });
                } else if (!endMarker) {
                    // 设置终点
                    endMarker = new BMap.Marker(point);
                    endMarker.setIcon(new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(23, 25)));
                    endMarker.setLabel(new BMap.Label("终点", {offset: new BMap.Size(20, 0)}));
                    map.addOverlay(endMarker);
                    
                    // 更新终点输入框
                    var gc = new BMap.Geocoder();
                    gc.getLocation(point, function(rs) {
                        var address = rs.address;
                        document.getElementById("end-input").value = address;
                    });
                } else {
                    // 重置起终点
                    clearRoutePlanningOverlays();
                    
                    // 设置新起点
                    startMarker = new BMap.Marker(point);
                    startMarker.setIcon(new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(23, 25)));
                    startMarker.setLabel(new BMap.Label("起点", {offset: new BMap.Size(20, 0)}));
                    map.addOverlay(startMarker);
                    
                    // 更新起点输入框
                    var gc = new BMap.Geocoder();
                    gc.getLocation(point, function(rs) {
                        var address = rs.address;
                        document.getElementById("start-input").value = address;
                    });
                    
                    // 清空终点输入框
                    document.getElementById("end-input").value = "";
                }
            });
        }
        
        // 搜索地点位置
        function searchLocation(type) {
            var keyword = '';
            if (type === 'start') {
                keyword = document.getElementById('start-input').value;
            } else if (type === 'end') {
                keyword = document.getElementById('end-input').value;
            }
            
            if (!keyword) {
                alert('请输入地点名称');
                return;
            }
            
            // 创建地址解析器实例
            var myGeo = new BMap.Geocoder();
            // 将地址解析结果显示在地图上，并调整地图视野
            myGeo.getPoint(keyword, function(point){
                if (point) {
                    if (type === 'start') {
                        // 清除之前的起点标记
                        if (startMarker) {
                            map.removeOverlay(startMarker);
                        }
                        
                        // 设置新起点
                        startMarker = new BMap.Marker(point);
                        startMarker.setIcon(new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(23, 25)));
                        startMarker.setLabel(new BMap.Label("起点", {offset: new BMap.Size(20, 0)}));
                        map.addOverlay(startMarker);
                        map.centerAndZoom(point, 16);
                    } else if (type === 'end') {
                        // 清除之前的终点标记
                        if (endMarker) {
                            map.removeOverlay(endMarker);
                        }
                        
                        // 设置新终点
                        endMarker = new BMap.Marker(point);
                        endMarker.setIcon(new BMap.Icon("https://api.map.baidu.com/images/marker_red_sprite.png", new BMap.Size(23, 25)));
                        endMarker.setLabel(new BMap.Label("终点", {offset: new BMap.Size(20, 0)}));
                        map.addOverlay(endMarker);
                        map.centerAndZoom(point, 16);
                    }
                } else {
                    alert("未找到该地点，请尝试更精确的名称");
                }
            }, "北京市");
        }
        
        // 规划路线
        function planRoute() {
            // 获取起点和终点
            var start = document.getElementById("start-input").value;
            var end = document.getElementById("end-input").value;
            
            if (!start || !end) {
                alert("请输入或选择起点和终点");
                return;
            }
            
            // 获取出行方式
            var routeTypeElements = document.getElementsByName("route-type");
            var routeType = "driving"; // 默认驾车
            for (var i = 0; i < routeTypeElements.length; i++) {
                if (routeTypeElements[i].checked) {
                    routeType = routeTypeElements[i].value;
                    break;
                }
            }
            
            // 清除已有的路线
            for (var i = 0; i < routeLines.length; i++) {
                map.removeOverlay(routeLines[i]);
            }
            routeLines = [];
            
            // 路线结果容器
            var routeResultDiv = document.getElementById("route-result");
            routeResultDiv.innerHTML = "<p>正在规划路线...</p>";
            
            // 修复：确保起点和终点是有效的坐标点
            if (!startMarker || !endMarker) {
                routeResultDiv.innerHTML = "<p style='color: red;'>请确保已正确设置起点和终点</p>";
                return;
            }
            
            var startPoint = startMarker.getPosition();
            var endPoint = endMarker.getPosition();
            
            // 使用后端代理API调用百度地图
            fetch(`/api/route?startLat=${startPoint.lat}&startLng=${startPoint.lng}&endLat=${endPoint.lat}&endLng=${endPoint.lng}&mode=${routeType}`)
                .then(response => {
                    if (!response.ok) {
                        throw new Error(`HTTP error! Status: ${response.status}`);
                    }
                    return response.json();
                })
                .then(data => {
                    console.log("路线规划结果:", data);
                    
                    // 处理API响应数据
                    if (data.status === 0 && data.result && data.result.routes && data.result.routes.length > 0) {
                        // 成功获取路线
                        var route = data.result.routes[0];
                        
                        // 显示路线信息
                        var html = "<div style='padding: 10px; background: #f9f9f9; border-radius: 5px;'>";
                        
                        // 根据不同出行方式显示标题
                        if (routeType === "driving") {
                            html += "<h3 style='margin-bottom: 10px;'>驾车路线</h3>";
                        } else if (routeType === "walking") {
                            html += "<h3 style='margin-bottom: 10px;'>步行路线</h3>";
                        } else if (routeType === "transit") {
                            html += "<h3 style='margin-bottom: 10px;'>公交路线</h3>";
                        }
                        
                        // 显示距离和时间
                        html += "<p><strong>总距离:</strong> " + (route.distance / 1000).toFixed(2) + " 公里</p>";
                        
                        // 转换时间显示格式
                        var durationMinutes = Math.round(route.duration / 60);
                        var durationHours = Math.floor(durationMinutes / 60);
                        var remainingMinutes = durationMinutes % 60;
                        
                        var durationText = "";
                        if (durationHours > 0) {
                            durationText += durationHours + "小时";
                        }
                        if (remainingMinutes > 0) {
                            durationText += remainingMinutes + "分钟";
                        }
                        
                        html += "<p><strong>预计用时:</strong> " + durationText + "</p>";
                        html += "<div style='margin-top: 10px;'><strong>路线详情:</strong></div>";
                        html += "<ol style='margin-top: 5px; padding-left: 20px;'>";
                        
                        // 添加路线步骤详情
                        if (routeType === "driving" || routeType === "walking") {
                            // 驾车或步行路线
                            route.steps.forEach(function(step) {
                                html += "<li>" + step.instruction + "</li>";
                            });
                        } else if (routeType === "transit") {
                            // 公交路线
                            route.steps.forEach(function(step) {
                                if (step.vehicle && step.vehicle.name) {
                                    html += "<li>乘坐 <strong>" + step.vehicle.name + "</strong>";
                                    if (step.vehicle.stop && step.vehicle.stop.length > 0) {
                                        html += " " + (step.vehicle.stop.length - 1) + "站";
                                    }
                                    html += "</li>";
                                } else if (step.distance > 0) {
                                    html += "<li>步行 " + (step.distance / 1000).toFixed(2) + "公里</li>";
                                }
                            });
                        }
                        
                        html += "</ol></div>";
                        routeResultDiv.innerHTML = html;
                        
                        // 在地图上绘制路线
                        drawRouteOnMap(route, routeType);
                        
                    } else {
                        // API返回错误
                        routeResultDiv.innerHTML = "<p style='color: red;'>路线规划失败: " + (data.message || "未知错误") + "</p>";
                        routeResultDiv.innerHTML += "<p>正在使用直线连接作为备选方案</p>";
                        
                        // 使用直线连接作为备选
                        showDirectLine(startPoint, endPoint);
                    }
                })
                .catch(error => {
                    console.error("路线规划请求失败:", error);
                    routeResultDiv.innerHTML = "<p style='color: red;'>路线规划请求失败: " + error.message + "</p>";
                    routeResultDiv.innerHTML += "<p>正在使用直线连接作为备选方案</p>";
                    
                    // 使用直线连接作为备选
                    showDirectLine(startPoint, endPoint);
                });
        }
        
        // 在地图上绘制路线
        function drawRouteOnMap(route, routeType) {
            // 清除已有的路线
            for (var i = 0; i < routeLines.length; i++) {
                map.removeOverlay(routeLines[i]);
            }
            routeLines = [];
            
            // 设置路线颜色
            var routeColor = "#3498db"; // 默认蓝色
            if (routeType === "driving") {
                routeColor = "#ff5722"; // 驾车路线橙色
            } else if (routeType === "walking") {
                routeColor = "#4caf50"; // 步行路线绿色
            } else if (routeType === "transit") {
                routeColor = "#9c27b0"; // 公交路线紫色
            }
            
            // 解析路线点
            var points = [];
            
            // 根据不同的路线类型解析点
            if (route.paths && route.paths.length > 0) {
                // Transit API格式
                route.paths.forEach(function(path) {
                    if (path.steps && path.steps.length > 0) {
                        path.steps.forEach(function(step) {
                            if (step.path) {
                                var stepPoints = parseRoutePoints(step.path);
                                points = points.concat(stepPoints);
                            }
                        });
                    }
                });
            } else if (route.steps && route.steps.length > 0) {
                // Driving/Walking API格式
                route.steps.forEach(function(step) {
                    if (step.path) {
                        var stepPoints = parseRoutePoints(step.path);
                        points = points.concat(stepPoints);
                    }
                });
            }
            
            // 如果找不到路线点，则使用起终点创建直线
            if (points.length === 0) {
                points.push(startMarker.getPosition());
                points.push(endMarker.getPosition());
            }
            
            // 创建折线对象
            var polyline = new BMap.Polyline(points, {
                strokeColor: routeColor,
                strokeWeight: 6,
                strokeOpacity: 0.8
            });
            
            // 添加到地图
            map.addOverlay(polyline);
            routeLines.push(polyline);
            
            // 调整地图视图
            map.setViewport(points);
        }
        
        // 解析路线点坐标
        function parseRoutePoints(pathString) {
            var points = [];
            if (!pathString) return points;
            
            var coordinates = pathString.split(';');
            coordinates.forEach(function(coord) {
                var lngLat = coord.split(',');
                if (lngLat.length === 2) {
                    var lng = parseFloat(lngLat[0]);
                    var lat = parseFloat(lngLat[1]);
                    if (!isNaN(lng) && !isNaN(lat)) {
                        points.push(new BMap.Point(lng, lat));
                    }
                }
            });
            
            return points;
        }
        
        // 在路线规划失败时显示直线连接
        function showDirectLine(startPoint, endPoint) {
            // 清除已有的路线
            for (var i = 0; i < routeLines.length; i++) {
                map.removeOverlay(routeLines[i]);
            }
            routeLines = [];
            
            // 创建直线
            var polyline = new BMap.Polyline([
                startPoint,
                endPoint
            ], {
                strokeColor: "#ff3300",
                strokeWeight: 4,
                strokeOpacity: 0.8,
                strokeStyle: "dashed"
            });
            
            // 添加到地图并保存
            map.addOverlay(polyline);
            routeLines.push(polyline);
            
            // 调整地图视图以包含起点和终点
            map.setViewport([startPoint, endPoint]);
            
            // 在直线中点添加提示信息
            var midPoint = new BMap.Point(
                (startPoint.lng + endPoint.lng) / 2,
                (startPoint.lat + endPoint.lat) / 2
            );
            
            // 计算直线距离（公里）
            var distance = map.getDistance(startPoint, endPoint) / 1000;
            distance = distance.toFixed(2);
            
            var infoWindow = new BMap.InfoWindow(
                "<div style='text-align:center; padding: 5px;'>" +
                "<p>直线距离: " + distance + " 公里</p>" +
                "<p style='color:#999; font-size:12px;'>注: 实际路线可能有所不同</p>" +
                "</div>"
            );
            
            // 在中点打开信息窗口
            map.openInfoWindow(infoWindow, midPoint);
        }

        // 显示地点模块内容
        function showPlacesModule() {
            const sideMenu = document.getElementById('side-menu');
            
            // 构建地点模块界面
            var menuHtml = "<div class=\"search-container\">";
            
            // 添加返回按钮到顶部
            menuHtml += "    <div style=\"margin-bottom: 15px;\">";
            menuHtml += "        <button onclick=\"resetInterface()\" style=\"padding: 8px 15px; background-color: #f1f1f1; border: 1px solid #ddd; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "            <i class=\"fas fa-arrow-left\"></i> 返回";
            menuHtml += "        </button>";
            menuHtml += "    </div>";
            
            menuHtml += "    <div class=\"search-title\">";
            menuHtml += "        <i class=\"fas fa-landmark\" style=\"margin-right: 10px; color: #3498db;\"></i>";
            menuHtml += "        地点推荐";
            menuHtml += "    </div>";
            menuHtml += "    <div class=\"search-input-group\">";
            menuHtml += "        <input type=\"text\" id=\"place-search-input\" class=\"search-input\" placeholder=\"搜索景点和学校...\">";
            menuHtml += "        <button class=\"search-button\" onclick=\"searchPlaces()\">";
            menuHtml += "            <i class=\"fas fa-search\"></i> 搜索";
            menuHtml += "        </button>";
            menuHtml += "    </div>";
            
            // 添加排序按钮
            menuHtml += "    <div style=\"display: flex; margin-top: 15px; gap: 10px;\">";
            menuHtml += "        <button id=\"popularity-btn\" onclick=\"sortPlaces('popularity')\" style=\"flex: 1; padding: 8px 0; background-color: #3498db; color: white; border: none; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "            <i class=\"fas fa-fire\"></i> 按热度排序";
            menuHtml += "        </button>";
            menuHtml += "        <button id=\"rating-btn\" onclick=\"sortPlaces('rating')\" style=\"flex: 1; padding: 8px 0; background-color: #f1f1f1; color: #333; border: 1px solid #ddd; border-radius: 5px; cursor: pointer;\">";
            menuHtml += "            <i class=\"fas fa-star\"></i> 按评价排序";
            menuHtml += "        </button>";
            menuHtml += "    </div>";
            
            // 添加结果区域
            menuHtml += "    <div id=\"places-results\" style=\"margin-top: 15px; max-height: calc(100vh - 250px); overflow-y: auto;\">";
            menuHtml += "        <div style=\"text-align: center; padding: 20px;\"><i class=\"fas fa-spinner fa-spin\"></i> 加载中...</div>";
            menuHtml += "    </div>";
            
            // 更新界面
            sideMenu.innerHTML = menuHtml;
            
            // 加载推荐地点
            loadRecommendedPlaces();
        }
        
        // 加载推荐地点
        function loadRecommendedPlaces() {
            // 显示加载中状态
            document.getElementById('places-results').innerHTML = 
                '<div style="text-align: center; padding: 20px;"><i class="fas fa-spinner fa-spin"></i> 加载中...</div>';
                
            // 获取搜索框内容
            const keyword = document.getElementById('place-search-input') ? 
                document.getElementById('place-search-input').value.trim() : '';
            
            console.log("当前搜索关键词: '" + keyword + "'");
            console.log("当前排序方式: " + currentSortMethod);
            
            // 如果搜索框存在且有内容，使用搜索API
            if (keyword) {
                console.log("使用搜索API");
                const searchApiPath = `/api/places/search?keyword=${encodeURIComponent(keyword)}&sortBy=${currentSortMethod}`;
                console.log("API路径: " + searchApiPath);
                
                fetch(searchApiPath)
                    .then(response => {
                        console.log("搜索API状态码: " + response.status);
                        if (!response.ok) {
                            throw new Error('网络请求失败: ' + response.status);
                        }
                        return response.json();
                    })
                    .then(places => {
                        console.log("搜索结果数: " + places.length);
                        
                        // 更新查询到的地点数据到全局变量
                        // 注意：此处不替换全部数据，只用于搜索结果
                        places.forEach(place => {
                            updatePlaceInGlobalData(place);
                        });
                        
                        displayPlaces(places);
                        updateSortButtons();
                    })
                    .catch(error => {
                        console.error('搜索地点失败:', error);
                        document.getElementById('places-results').innerHTML = 
                            '<div style="text-align: center; padding: 20px; color: #e74c3c;">搜索失败，请重试</div>';
                    });
            } 
            // 如果搜索框为空，使用全局地点数据
            else {
                console.log("使用全局数据并在前端过滤景点和学校");
                
                // 确保全局数据已加载
                refreshPlacesData()
                    .then(() => {
                        displayPlacesFromGlobalData();
                        updateSortButtons();
                    })
                    .catch(error => {
                        console.error('加载推荐地点失败:', error);
                        document.getElementById('places-results').innerHTML = 
                            '<div style="text-align: center; padding: 20px; color: #e74c3c;">加载失败，请重试</div>';
                    });
            }
        }
        
        // 从全局数据中显示地点
        function displayPlacesFromGlobalData() {
            // 只选择景点和学校
            let filteredPlaces = placesData.filter(place => 
                place.type === '景点' || place.type === '学校');
            
            console.log("景点和学校数量: " + filteredPlaces.length);
            
            // 根据当前排序方式排序
            if (currentSortMethod === "popularity") {
                filteredPlaces.sort((a, b) => b.popularity - a.popularity);
            } else { // rating
                filteredPlaces.sort((a, b) => b.rating - a.rating);
            }
            
            // 只取前10个
            filteredPlaces = filteredPlaces.slice(0, 10);
            
            console.log("最终显示数量: " + filteredPlaces.length);
            displayPlaces(filteredPlaces);
        }
        
        // 搜索地点
        function searchPlaces() {
            // 统一使用loadRecommendedPlaces函数处理搜索和推荐
            loadRecommendedPlaces();
        }
        
        // 切换排序方式
        function sortPlaces(sortMethod) {
            if (currentSortMethod === sortMethod) return; // 如果已经是当前排序方法，无需操作
            
            // 更新当前排序方式
            currentSortMethod = sortMethod;
            
            // 无论搜索框是否有内容，都使用loadRecommendedPlaces加载排序后的数据
            loadRecommendedPlaces();
            
            // 更新排序按钮样式
            updateSortButtons();
        }
        
        // 更新排序按钮样式
        function updateSortButtons() {
            const popularityBtn = document.getElementById('popularity-btn');
            const ratingBtn = document.getElementById('rating-btn');
            
            if (currentSortMethod === "popularity") {
                popularityBtn.style.backgroundColor = "#3498db";
                popularityBtn.style.color = "white";
                popularityBtn.style.border = "none";
                
                ratingBtn.style.backgroundColor = "#f1f1f1";
                ratingBtn.style.color = "#333";
                ratingBtn.style.border = "1px solid #ddd";
            } else {
                ratingBtn.style.backgroundColor = "#3498db";
                ratingBtn.style.color = "white";
                ratingBtn.style.border = "none";
                
                popularityBtn.style.backgroundColor = "#f1f1f1";
                popularityBtn.style.color = "#333";
                popularityBtn.style.border = "1px solid #ddd";
            }
        }
        
        // 显示地点列表
        function displayPlaces(places) {
            const resultsContainer = document.getElementById('places-results');
            
            if (!places || places.length === 0) {
                resultsContainer.innerHTML = '<div style="text-align: center; padding: 20px;">未找到相关地点</div>';
                return;
            }
            
            let html = "";
            places.forEach(place => {
                html += `<div class="place-item" onclick="showPlaceOnMap(${place.latitude}, ${place.longitude}, ${place.id})" 
                              style="padding: 15px; margin-bottom: 10px; background-color: white; border-radius: 5px; 
                                     box-shadow: 0 2px 5px rgba(0,0,0,0.1); cursor: pointer;">`;
                html += `    <h3 style="margin: 0 0 8px; color: #3498db;">${place.name}</h3>`;
                html += `    <p style="margin: 0 0 5px; font-size: 14px; color: #666;"><i class="fas fa-map-marker-alt" style="color: #e74c3c;"></i> ${place.type}</p>`;
                html += `    <p style="margin: 0 0 5px; font-size: 14px; color: #666; white-space: nowrap; overflow: hidden; text-overflow: ellipsis;">
                               <i class="fas fa-map-pin" style="color: #3498db;"></i> ${place.address || '地址未知'}</p>`;
                
                // 显示热度和评价
                html += `    <div style="display: flex; margin-top: 8px; font-size: 13px;">`;
                html += `        <div style="display: flex; align-items: center; margin-right: 15px;">`;
                html += `            <i class="fas fa-fire" style="color: #f39c12; margin-right: 5px;"></i>`;
                html += `            <span>热度: ${parseFloat(place.popularity).toFixed(1)}</span>`;
                html += `        </div>`;
                html += `        <div style="display: flex; align-items: center;">`;
                html += `            <i class="fas fa-star" style="color: #f1c40f; margin-right: 5px;"></i>`;
                html += `            <span>评价: ${place.rating ? parseFloat(place.rating).toFixed(1) : '暂无'}</span>`;
                html += `        </div>`;
                html += `    </div>`;
                
                html += `</div>`;
            });
            
            resultsContainer.innerHTML = html;
        }
        
        // 在地图上显示地点
        function showPlaceOnMap(lat, lng, placeId) {
            // 直接跳转到单独的地点页面
            window.location.href = `/place/${placeId}`;
        }
        
        // 评价地点
        function ratePlace(placeId) {
            // 创建评分弹窗
            var ratingHtml = `
                <div style="padding: 15px; text-align: center;">
                    <h3 style="margin-bottom: 15px;">为此地点评分</h3>
                    <div style="display: flex; justify-content: center; margin-bottom: 15px;">
                        <div class="rating">
                            <i class="fas fa-star" data-rating="1" style="color: #ddd; font-size: 24px; margin: 0 5px; cursor: pointer;"></i>
                            <i class="fas fa-star" data-rating="2" style="color: #ddd; font-size: 24px; margin: 0 5px; cursor: pointer;"></i>
                            <i class="fas fa-star" data-rating="3" style="color: #ddd; font-size: 24px; margin: 0 5px; cursor: pointer;"></i>
                            <i class="fas fa-star" data-rating="4" style="color: #ddd; font-size: 24px; margin: 0 5px; cursor: pointer;"></i>
                            <i class="fas fa-star" data-rating="5" style="color: #ddd; font-size: 24px; margin: 0 5px; cursor: pointer;"></i>
                        </div>
                    </div>
                    <div>
                        <button id="submit-rating" style="padding: 8px 15px; background-color: #3498db; color: white; border: none; border-radius: 3px; cursor: pointer; margin-right: 10px;" disabled>
                            提交评分
                        </button>
                        <button onclick="cancelRating()" style="padding: 8px 15px; background-color: #f1f1f1; border: 1px solid #ddd; border-radius: 3px; cursor: pointer;">
                            取消
                        </button>
                    </div>
                </div>
            `;
            
            // 显示评分弹窗
            var ratingDiv = document.createElement('div');
            ratingDiv.style.position = 'fixed';
            ratingDiv.style.top = '50%';
            ratingDiv.style.left = '50%';
            ratingDiv.style.transform = 'translate(-50%, -50%)';
            ratingDiv.style.background = '#fff';
            ratingDiv.style.borderRadius = '5px';
            ratingDiv.style.boxShadow = '0 0 10px rgba(0,0,0,0.3)';
            ratingDiv.style.zIndex = '9999';
            ratingDiv.innerHTML = ratingHtml;
            document.body.appendChild(ratingDiv);
            
            // 添加遮罩层
            var overlay = document.createElement('div');
            overlay.style.position = 'fixed';
            overlay.style.top = '0';
            overlay.style.left = '0';
            overlay.style.width = '100%';
            overlay.style.height = '100%';
            overlay.style.background = 'rgba(0,0,0,0.5)';
            overlay.style.zIndex = '9998';
            document.body.appendChild(overlay);
            
            // 评分变量
            var selectedRating = 0;
            
            // 为星星添加交互
            var stars = ratingDiv.querySelectorAll('.rating i');
            stars.forEach(function(star) {
                // 鼠标悬停效果
                star.addEventListener('mouseover', function() {
                    var rating = parseInt(this.getAttribute('data-rating'));
                    highlightStars(rating);
                });
                
                // 鼠标移出效果
                star.addEventListener('mouseout', function() {
                    highlightStars(selectedRating);
                });
                
                // 点击选择评分
                star.addEventListener('click', function() {
                    selectedRating = parseInt(this.getAttribute('data-rating'));
                    highlightStars(selectedRating);
                    
                    // 启用提交按钮
                    document.getElementById('submit-rating').disabled = false;
                });
            });
            
            // 高亮星星函数
            function highlightStars(rating) {
                stars.forEach(function(star) {
                    var starRating = parseInt(star.getAttribute('data-rating'));
                    if (starRating <= rating) {
                        star.style.color = '#f1c40f';
                    } else {
                        star.style.color = '#ddd';
                    }
                });
            }
            
            // 提交评分
            document.getElementById('submit-rating').addEventListener('click', function() {
                if (selectedRating > 0) {
                    // 发送评分到API
                    fetch(`/api/places/${placeId}/rate`, {
                        method: 'POST',
                        headers: {
                            'Content-Type': 'application/json'
                        },
                        body: JSON.stringify({
                            rating: selectedRating
                        })
                    })
                    .then(response => {
                        if (!response.ok) {
                            throw new Error('评分失败');
                        }
                        return response.json();
                    })
                    .then(data => {
                        console.log('评分成功:', data);
                        // 关闭评分弹窗
                        document.body.removeChild(ratingDiv);
                        document.body.removeChild(overlay);
                        
                        // 更新全局数据
                        fetch(`/api/places/${placeId}`)
                            .then(response => response.json())
                            .then(updatedPlace => {
                                // 更新全局数据
                                updatePlaceInGlobalData(updatedPlace);
                                
                                // 刷新地点信息
                                for (var i = 0; i < markers.length; i++) {
                                    if (markers[i].placeId === placeId) {
                                        markers[i].dispatchEvent("click");
                                        break;
                                    }
                                }
                                
                                // 如果在搜索结果中，刷新搜索结果
                                if (document.getElementById('places-results')) {
                                    displayPlacesFromGlobalData();
                                }
                            })
                            .catch(error => {
                                console.error('更新地点数据失败:', error);
                            });
                        
                        // 显示评分成功提示
                        alert('评分成功，感谢您的反馈！');
                    })
                    .catch(error => {
                        console.error('评分失败:', error);
                        alert('评分失败，请稍后重试');
                    });
                }
            });
        }
        
        // 取消评分
        function cancelRating() {
            var ratingDiv = document.querySelector('div[style*="z-index: 9999"]');
            var overlay = document.querySelector('div[style*="z-index: 9998"]');
            
            if (ratingDiv) document.body.removeChild(ratingDiv);
            if (overlay) document.body.removeChild(overlay);
        }
    </script>
</body>
</html> 
